package org.example.domain.strategy.service.rule.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.RuleActionEntity;
import org.example.domain.strategy.model.entity.RuleMatterEntity;
import org.example.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import org.example.domain.strategy.repository.IStrategyRuleRepository;
import org.example.domain.strategy.service.annotation.LogicStrategy;
import org.example.domain.strategy.service.rule.ILogicFilter;
import org.example.domain.strategy.service.rule.factory.DefaultLogicFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_BLACKLIST)
public class RuleBackListLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {
    @Resource
    IStrategyRuleRepository strategyRuleRepository;
    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        //查询是否配置黑名单
        String ruleValue = strategyRuleRepository.queryRuleValue(ruleMatterEntity.getStrategyId(), ruleMatterEntity.getAwardId(), ruleMatterEntity.getRuleModel());
        if (null != ruleValue) {
            String[] ruleFormat = ruleValue.split(Constants.COLON);
            Long awardId = Long.valueOf(ruleFormat[0]);
            String userList = ruleFormat[1];
            List<Long> userListFormat = Arrays.stream(userList.split(Constants.SPLIT)).map(Long::valueOf).toList();
            if (userListFormat.contains(ruleMatterEntity.getUserId())) {
                //黑名单用户直接返回
                return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                    .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                    .ruleModel(ruleMatterEntity.getRuleModel())
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                         .StrategyId(ruleMatterEntity.getStrategyId())
                         .awardId(awardId)
                         .build()).build();
            }

        }

        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }
}
